/*
 * HttpRequest.cpp
 *
 *  Created on: 03.12.2012
 *      Author: zheka
 */

#include "HttpRequest.hpp"
#include "util/StringUtils.hpp"
#include <sstream>
#include "HttpConstants.hpp"

/**
 * Skip "Proxy-Connection" field
 */
void HttpRequest::addHeader(const std::string & key,
		const std::string & value) {
	if (key == "Proxy-Connection")
		return;
	/*if(key=="Accept-Encoding") {
	 return;
	 }*/
	HttpBaseHeader::addHeader(key, value);
}
/**
 *  on some browser it may be like "http://site.com/query" but must be "/query"
 */
void HttpRequest::setHttpQuery(const std::string & httpQuery) {
	const std::string scheme = "http://";
	const std::string delim = "/";
	if (httpQuery.find(scheme) != std::string::npos) {
		int pos = httpQuery.find(delim, scheme.length());

		this->httpQuery = httpQuery.substr(pos);
	} else {
		this->httpQuery = httpQuery;
	}
}

std::string HttpRequest::getHttpQuery() const {
	std::map<std::string, std::string>::const_iterator it = headers.find(
			"Host");
	return it->second + httpQuery;
}
std::string HttpRequest::getHttpMethod() const {

	return httpMethod;
}
void HttpRequest::setHttpMethod(const std::string & httpMethod) {

	this->httpMethod = httpMethod;
}
std::string HttpRequest::toString() const {
	std::stringstream out;

	out << HttpConstants::HTTP_METHOD << " " << httpQuery << " " << httpVersion
			<< HttpConstants::HTTP_NEWLINE;

	out << HttpBaseHeader::toString();

	out << HttpConstants::HTTP_NEWLINE;

	return out.str();
}
ConnectionInfo HttpRequest::getConnectionInfo() const {

	std::map<std::string, std::string>::const_iterator it = headers.find(
			"Host");
	std::string host = it->second;
	int port = HttpConstants::HTTP_DEFAULT_PORT;
	size_t pos = host.find(":");
	if (pos != std::string::npos) {
		port = StringUtils::toInteger(host.substr(pos + 1));
		host = host.substr(0, pos);
	}
	return ConnectionInfo(host, port);
}

